package com.rongdu.workflow.controller;

import java.io.IOException;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/ProcessInstanceAction")
public class ProcessInstanceAction {
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	IdentityService identityService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/startProcessInstance.do")
	public void startProcessInstance(String processDefinitionId, String variables, String businessKey) {
		ObjectMapper  mapper = new ObjectMapper();
		
		Map<String, Object> bpmVariables = null;
		try {
			bpmVariables = mapper.readValue(variables, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String authenticatedUserId = getLoginUser(bpmVariables);
		
		identityService.setAuthenticatedUserId(authenticatedUserId);
		
		ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, businessKey, bpmVariables);
	}
	
	private String getLoginUser(Map<String, Object> bpmVariables) {
		return (String) bpmVariables.get("loginUserId");
	}

	@RequestMapping("/queryAll.do")
	public void queryAll() {
		
	}
}
